package com.gomore.opple.module.orderpay;

import android.text.TextUtils;

import com.gomore.opple.common.GlobalConstant;
import com.gomore.opple.data.DataRepository;
import com.gomore.opple.data.remote.bean.result.WeChatResult;
import com.gomore.opple.data.remote.retrofit.HttpResponseFunc;
import com.gomore.opple.data.remote.retrofit.RxSubscriber;
import com.gomore.opple.data.remote.retrofit.ServerResponseFunc;
import com.gomore.opple.exception.ApiException;
import com.gomore.opple.model.Action;
import com.gomore.opple.model.ActionResult;
import com.gomore.opple.model.WeChatData;
import com.gomore.opple.rest.employee.LoginResult;
import com.gomore.opple.rest.order.OrderBill;
import com.gomore.opple.rest.order.OrderPayRequest;
import com.gomore.opple.rest.order.RsOrderShareResponse;
import com.gomore.opple.rest.promotion.RsActionResult;
import com.gomore.opple.web.cgform.consumer.entity.TOConsumerEntity;
import com.gomore.opple.web.cgform.orderpromotion.entity.TOOrderPromotionEntity;
import com.gomore.opple.web.system.pojo.TOReseller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.inject.Inject;

import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

public class OrderPayPresenter implements OrderPayContract.Presenter {

    private DataRepository mDataRepositroy;
    private final OrderPayContract.View mView;
    private CompositeSubscription mSubscriptions;
    private List<Action> consumerActionList = new ArrayList<>();
    private List<Action> guideActionList = new ArrayList<>();
    private List<TOOrderPromotionEntity> toOrderPromotionEntities = new ArrayList<>();
    private RsOrderShareResponse rsOrderShareResponse;
    private WeChatData weChatData;

    @Inject
    OrderPayPresenter(DataRepository dataRepository, OrderPayContract.View view) {
        mDataRepositroy = dataRepository;
        mView = view;
        mSubscriptions = new CompositeSubscription();
        mView.setPresenter(this);
    }


    @Override
    public void subscribe() {

    }

    @Override
    public void unsubscribe() {
        mSubscriptions.clear();
    }

    /**
     * 初始化数据
     */
    @Override
    public void prepareInitData() {
        if (mDataRepositroy.getConsumer() != null) {
            mView.showConsumerView(mDataRepositroy.getConsumer());
        }
    }

    @Override
    public void getOrder(final String order_number, final String promotionType, final int viewType) {
        unsubscribe();
        mView.showProgressDialog();
        final Subscription subscription = mDataRepositroy.getOrderByNumber(order_number)
                .map(new ServerResponseFunc<OrderBill>())
                .onErrorResumeNext(new HttpResponseFunc<OrderBill>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<OrderBill>() {
                    @Override
                    public void onNext(OrderBill orderBill) {
                        super.onNext(orderBill);
                        mView.hideProgressDialog();
                        mView.showContentView(orderBill, viewType);
                        if (promotionType.equals(GlobalConstant.PromotionType.PROMOTIONSERVICE)) {
                            getCalc(order_number);
                        }
                        if (promotionType.equals(GlobalConstant.PromotionType.ORDERPROMOTIONSERVICE)) {
                            getOrderPromotion(order_number);
                        }
                    }

                    @Override
                    protected void onError(ApiException ex) {
                        mView.hideProgressDialog();
                    }
                });
        mSubscriptions.add(subscription);
    }

    @Override
    public void getCalc(String orderNumber) {
        unsubscribe();
        consumerActionList.clear();
        guideActionList.clear();
        mView.showProgressDialog();
        Subscription subscription = mDataRepositroy.getCalc(orderNumber)
                .map(new ServerResponseFunc<ActionResult>())
                .onErrorResumeNext(new HttpResponseFunc<ActionResult>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<ActionResult>() {
                    @Override
                    public void onNext(ActionResult actionResult) {
                        super.onNext(actionResult);
                        mView.hideProgressDialog();
                        //分类
                        categoryAction(actionResult.getActions());
                        //排序
                        sortByPriority(consumerActionList);
                        //促销条件选择
                        selectCondition(consumerActionList);
                        if (consumerActionList.size() > 0) {
                            mView.showConditionSelect();
                        }
                    }

                    @Override
                    protected void onError(ApiException ex) {
                        mView.hideProgressDialog();
                    }
                });
        mSubscriptions.add(subscription);
    }

    @Override
    public List<Action> getConsumerActionData() {
        return consumerActionList;
    }

    @Override
    public List<Action> getGuideActionData() {
        return guideActionList;
    }

    @Override
    public void getReseller(final String payMethod) {
        unsubscribe();
        mView.showProgressDialog();
        final Subscription subscription = mDataRepositroy.getReseller()
                .map(new ServerResponseFunc<TOReseller>())
                .onErrorResumeNext(new HttpResponseFunc<TOReseller>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<TOReseller>() {
                    @Override
                    public void onNext(TOReseller toReseller) {
                        super.onNext(toReseller);
                        mView.hideProgressDialog();
                        if (toReseller == null) {
                            return;
                        }
                        if (payMethod.equals(GlobalConstant.PayMethodOnLine.WEIXIN)) {
                              if(TextUtils.isEmpty(toReseller.getWeixin())){
                                  mView.showMessage("微信支付暂停使用");
                                  return;
                              }
                        } else {
                            if(TextUtils.isEmpty(toReseller.getZhifubao())){
                                mView.showMessage("支付宝支付暂停使用");
                                return;
                            }
                        }
                        mView.showCodeDialog(payMethod, toReseller);
                    }

                    @Override
                    protected void onError(ApiException ex) {
                        mView.hideProgressDialog();
                    }
                });
        mSubscriptions.add(subscription);
    }

    @Override
    public LoginResult getUser() {
        return mDataRepositroy.getUser();
    }

    @Override
    public void payOrder(OrderPayRequest orderPayRequest, final String orderNumber, final String promotionType,
                         final int viewType) {
        unsubscribe();
        mView.showProgressDialog();
        final Subscription subscription = mDataRepositroy.payOrder(orderPayRequest)
                .map(new ServerResponseFunc<String>())
                .onErrorResumeNext(new HttpResponseFunc<String>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<String>() {
                    @Override
                    public void onNext(String string) {
                        super.onNext(string);
                        mView.hideProgressDialog();
//                        getOrder(orderNumber, promotionType, viewType);
                        if (guideActionList.size() == 0) {
                            mView.goToOrderActivity();
                        } else {
                            mView.showResultDialog();
                        }
                    }

                    @Override
                    protected void onError(ApiException ex) {
                        mView.hideProgressDialog();
                        mView.showMessage(ex.message);
                    }
                });
        mSubscriptions.add(subscription);
    }

    @Override
    public void shareOrder(String order_number) {
        unsubscribe();
        mView.showProgressDialog();
        final Subscription subscription = mDataRepositroy.orderShare(order_number)
                .map(new ServerResponseFunc<RsOrderShareResponse>())
                .onErrorResumeNext(new HttpResponseFunc<RsOrderShareResponse>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<RsOrderShareResponse>() {
                    @Override
                    public void onNext(RsOrderShareResponse response) {
                        super.onNext(response);
                        mView.hideProgressDialog();
                        rsOrderShareResponse = response;
                        mView.showShareView();
                    }

                    @Override
                    protected void onError(ApiException ex) {
                        mView.hideProgressDialog();
                    }
                });
        mSubscriptions.add(subscription);
    }

    @Override
    public RsOrderShareResponse getShareUrl() {
        return rsOrderShareResponse;
    }

    @Override
    public void updateOrderState(final String orderNumber, String oldState, String newState, final String promotionType, final int viewType) {
        unsubscribe();
        mView.showProgressDialog();
        final Subscription subscription = mDataRepositroy.updateOrderState(orderNumber, oldState, newState)
                .map(new ServerResponseFunc<String>())
                .onErrorResumeNext(new HttpResponseFunc<String>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<String>() {
                    @Override
                    public void onNext(String str) {
                        super.onNext(str);
                        mView.hideProgressDialog();
                        getOrder(orderNumber, promotionType, viewType);
                    }

                    @Override
                    protected void onError(ApiException ex) {
                        mView.hideProgressDialog();
                    }
                });
        mSubscriptions.add(subscription);
    }

    @Override
    public void getWenChat(String cardNumber, String orderNumber, String orderTotal) {
        mView.showProgressDialog();
        mDataRepositroy.getWeChat(cardNumber, orderNumber, orderTotal)
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<WeChatResult>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.hideProgressDialog();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(WeChatResult weChatResult) {
                        mView.hideProgressDialog();
                        if (weChatResult.getData() == null) {
                            //弹出报错信息
                            mView.showMessage(weChatResult.getMsg());
                            //从新弹出选则框
                            mView.showConditionSelect();
                            return;
                        }
                        weChatData = weChatResult.getData();
                        for (int i = 0; i < consumerActionList.size(); i++) {
                            Action action = consumerActionList.get(i);
                            if (action.isSelect() && action.getType().equals(GlobalConstant.consumerConditionType.WXCARDACTION)) {
                                action.setIsUsed(true);
                                break;
                            }
                        }
                        mView.doActions();
                    }
                });
    }

    @Override
    public WeChatData getWeChatData() {
        return weChatData;
    }

    @Override
    public void getOrderPromotion(String orderNumber) {
        unsubscribe();
        mView.showProgressDialog();
        Subscription subscription = mDataRepositroy.getOrderPromotion(orderNumber)
                .map(new ServerResponseFunc<List<TOOrderPromotionEntity>>())
                .onErrorResumeNext(new HttpResponseFunc<List<TOOrderPromotionEntity>>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<List<TOOrderPromotionEntity>>() {
                    @Override
                    public void onNext(List<TOOrderPromotionEntity> toOrderPromotionEntityList) {
                        super.onNext(toOrderPromotionEntityList);
                        mView.hideProgressDialog();
                        //进行过滤
                        sortConsumerOrderPromotion(toOrderPromotionEntityList);
                        if (toOrderPromotionEntities.size() > 0) {
                            mView.showOrderPromotionContent();
                        }
                    }

                    @Override
                    protected void onError(ApiException ex) {
                        mView.hideProgressDialog();
                        mView.showMessage(ex.message);
                    }
                });
        mSubscriptions.add(subscription);
    }

    @Override
    public List<TOOrderPromotionEntity> getOrderPromotionData() {
        return toOrderPromotionEntities;
    }

    //给条件进行分类
    private void categoryAction(List<Action> actionList) {
        for (int i = 0; i < actionList.size(); i++) {
            Action action = actionList.get(i);
            if (action == null) {
                continue;
            }
            if (action.getBody().equals(GlobalConstant.PersonType.CONSUMER)) {
                consumerActionList.add(action);
            } else {
                guideActionList.add(action);
            }
        }
    }

    //根据Action里面的Priority排序(冒泡排序,从大到小)
    private void sortByPriority(List<Action> list) {
        Action[] courseTopics = list.toArray(new Action[list.size()]);
        Action temp; // 记录临时中间值
        for (int i = 0; i < courseTopics.length - 1; i++) {
            for (int j = i + 1; j < courseTopics.length; j++) {
                if (courseTopics[i].getPriority() < courseTopics[j].getPriority()) { // 交换两数的位置
                    temp = courseTopics[i];
                    courseTopics[i] = courseTopics[j];
                    courseTopics[j] = temp;
                }
            }
        }
        list.clear();
        list.addAll(Arrays.asList(courseTopics));
    }

    //对促销条件进行选择
    private void selectCondition(List<Action> list) {
        Action action = list.get(0);
        action.setIsSelect(true);
        String conflict = action.getConflicts().toString();
        for (int i = 0; i < list.size(); i++) {
            if (!conflict.contains(list.get(i).getType()) && !list.get(i).getType().equals(action.getType())) {
                //如果冲突为空，直接选择
                if (list.get(i).getConflicts().size() == 0) {
                    list.get(i).setIsSelect(true);
                } else {
                    for (int j = 0; j < list.get(i).getConflicts().size(); j++) {
                        String conflictStr = list.get(i).getConflicts().toString();
                        if (!conflictStr.contains(action.getType())) {
                            list.get(i).setIsSelect(true);
                        }
                    }
                }
            }
        }
    }

    //商品促销条件筛选
    private void sortConsumerOrderPromotion(List<TOOrderPromotionEntity> toOrderPromotionEntityList) {
        for (int i = 0; i < toOrderPromotionEntityList.size(); i++) {
            TOOrderPromotionEntity toOrderPromotionEntity = toOrderPromotionEntityList.get(i);
            if (toOrderPromotionEntity == null) {
                continue;
            }
            if (toOrderPromotionEntity.getBody().name().equals(GlobalConstant.PersonType.CONSUMER)) {
                toOrderPromotionEntities.add(toOrderPromotionEntity);
            }
        }
    }
}
